package com.aoxin.util.md5;

import java.security.MessageDigest;

/**
 * MD5工具类
 */
public class Md5Util {

    private static ThreadLocal<MessageDigest> MD5 = new ThreadLocal<MessageDigest>() {
        @Override
        protected MessageDigest initialValue() {
            try {
                return MessageDigest.getInstance("MD5");
            } catch (Exception e) {
            }
            return null;
        }
    };

    public static String md5(String text) {
        try {
            return md5(text.getBytes("utf-8"));
        } catch (Exception e) {
            return null;
        }
    }

    public static String md5(byte[] data) {
        MessageDigest md5 = MD5.get();
        md5.reset();
        md5.update(data);
        byte[] digest = md5.digest();
        return encodeHex(digest);
    }
    public static void main(String[] args) {

        System.err.println(md5("1"));
    }




    private static final char[] DIGITS_LOWER =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    public static String encodeHex(final byte[] data) {
        final int l = data.length;
        final char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS_LOWER[0x0F & data[i]];
        }
        return new String(out);
    }
}
